package utils;

import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.PerRequestConfig;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Http工具类
 */
public class HttpUtil {
	/**
	 * http非阻塞调用超时时间，单位毫秒。
	 */
	public static int HTTP_TIMEOUT = 30000;
	public static int READ_TIMEOUT = 30000;
	
	//POST请求
	public String requestful(final String url, Object obj) throws Exception {
		try {
			URL fullurl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) fullurl.openConnection();
			conn.setRequestMethod("POST");// 提交模式
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(HTTP_TIMEOUT);
			conn.setReadTimeout(READ_TIMEOUT);

			DataOutputStream out = new DataOutputStream(conn.getOutputStream());
			// 正文，正文内容其实跟get的URL中'?'后的参数字符串一致
			String content = "params=" + URLEncoder.encode(obj.toString(), "utf-8");
			// DataOutputStream.writeBytes将字符串中的16位的 unicode字符以8位的字符形式写道流里面
			out.writeBytes(content);

			out.flush();
			out.close();
			InputStream in = conn.getInputStream();
			StringBuilder sb = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in,"utf-8"));
			String s = "";
			while((s = reader.readLine()) != null){
				sb.append(s);
			}
			reader.close();
			in.close();
			String jsonresponse = new String(sb);

			return jsonresponse;
		} catch (Exception e) {
			//LogUtil.logerror(url + "请求调用失败", e);
			throw e;
		}
	}
	
	//GET请求
	public String requestByGET(final String url, Map<String, String> params) throws Exception {
		try {
			StringBuilder param = new StringBuilder().append("?");
			for(String key : params.keySet()){
				param.append(key).append("=" + URLEncoder.encode(params.get(key), "utf-8"));
			}
			URL fullurl = new URL(url+param.toString());
			HttpURLConnection conn = (HttpURLConnection) fullurl.openConnection();
			conn.setRequestMethod("GET");// 提交模式
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(HTTP_TIMEOUT);
			conn.setReadTimeout(READ_TIMEOUT);
			
			InputStream in = conn.getInputStream();
			StringBuilder sb = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in,"utf-8"));
			String s = "";
			while((s = reader.readLine()) != null){
				sb.append(s);
			}
			reader.close();
			in.close();
			String jsonresponse = new String(sb);

			return jsonresponse;
		} catch (Exception e) {
			//LogUtil.logerror(url + "请求调用失败", e);
			throw e;
		}
	}

	//异步请求
	public void asyncrequestful(AsyncHttpClient client, String url, Map<String, String> request, AsyncHandler<String> handler) throws IOException {
		// 发送请求（返回json字符串）
		BoundRequestBuilder builder = client.preparePost(url);
		PerRequestConfig perRequestConfig = new PerRequestConfig();
		perRequestConfig.setRequestTimeoutInMs(HTTP_TIMEOUT);
		builder.setPerRequestConfig(perRequestConfig);
		for (String key : request.keySet()) {
			builder.addParameter(key, request.get(key));
		}
		try {
			builder.execute(handler);
		} catch (IOException e) {
			client.close();
			LogUtil.logerror("异步http请求失败", e);
			throw e;
		}
	}
}
